package com.yunxin.core.domain.service.warn.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import com.yunxin.core.application.dto.user.UserInfoPageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class SendMsgService {



    @Value("${sms.gateway.url}")
    private String url;

    @Value("${sms.gateway.code}")
    private String code;

    @Value("${sms.gateway.key}")
    private String key;

    @Value("${sms.gateway.secret}")
    private String secret;


    /**
     *
     * @param phones 号码
     * @param content 短信内容
     * @param title 日志标题
     */
    public void send(List<String> phones,String content,String title) {


        if (CollUtil.isEmpty(phones)) {
            return;
        }


        String phone = String.join(",", phones);
        // 获取时间戳
        long timestamp = System.currentTimeMillis();
        // 生成签名
        String sign = key + secret + timestamp;
        // md5加密
        String md5Sign = SecureUtil.md5(sign).toLowerCase();


        HttpRequest request = HttpRequest.post(url + "/sms/batch/v1");

        // 添加参数
        JSONObject requestParam = new JSONObject();
        requestParam.put("appkey", key);
        requestParam.put("appcode", code);
        requestParam.put("sign", md5Sign);
        requestParam.put("phone", phone);
        requestParam.put("msg", content);
        requestParam.put("timestamp", timestamp);

        // 设置请求方式
        request.method(Method.POST);
        // 传参方式
        request.contentType("application/json;charset=utf-8");
        // 添加参数
        request.body(requestParam.toString());
        // 发送请求
        HttpResponse response = null;
        try {
            response = request.execute();
        } catch (Exception e) {
            log.error("{}短信发送请求异常：{}",title, ExceptionUtil.stacktraceToString(e));
        }
        // 获取返回值
        String body = response.body();
        // 转json
        JSONObject jsonObject = new JSONObject(body);
        if (!Objects.equals(jsonObject.getStr("code"), "00000")) {
            log.error("{}-短信平台响应异常,异常信息{}",title, jsonObject.getStr("desc"));
        }
    }

}
